package com.zzw.thread;

import java.util.concurrent.locks.ReentrantLock;

public class AccountLock {

	private final ReentrantLock lock = new ReentrantLock();
	private String accountNo;
	private double balance;
	public AccountLock(){
		
	}
	
	public AccountLock(String accountNo,double balance){
		this.accountNo = accountNo;
		this.balance = balance;
	}

	public String getAccountNo() {
		return accountNo;
	}
	
	public static void main(String[] args) {
		final AccountLock lock = new AccountLock("123456", 1000);
		new Thread(new Runnable() {
			@Override
			public void run() {
				lock.draw(1000);
			}
		},"甲").start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				lock.draw(1000);
			}
		},"乙").start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				lock.draw(1000);
			}
		},"丙").start();
	}
	
	public void draw(double drawAmount){
		lock.lock();
		try {
			if(balance >= drawAmount){
				System.out.println("" + drawAmount);
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				balance -= drawAmount;
				System.out.println("" + balance);
			}
			else{
				System.out.println(Thread.currentThread().getName() + "");
			}
		} finally {
			lock.unlock();
		}
	}

	@Override
	public int hashCode() {
		return accountNo.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(this == obj){
			return true;
		}
		else if(obj != null && obj.getClass() == Account.class){
			Account target = (Account) obj;
			return target.getAccountNo().equals(accountNo);
		}
		return false;
	}
	
	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	public double getBalance() {
		return balance;
	}

	/*public void setBalance(double balance) {
		this.balance = balance;
	}*/
}
